package com.mvc.util;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.mvc.config.ActionForward;
import com.mvc.config.ConfigBean;

/**
 * mvc配置解析器
 * @author asus
 *
 */

public class XmlParser {
	
	public static Map<String, ConfigBean> parser(String url) {
		SAXReader reader = new SAXReader();
		Document document = null;
		Map<String, ConfigBean> configBean = new HashMap<String, ConfigBean>();
		try {
			document = reader.read(url);
			Element root = document.getRootElement();
			
			//解析form-beans
			Map<String, Element> beansMap = new HashMap<String, Element>();
			Element formBeans = root.element("form-beans");
			List<Element> beanList = formBeans.elements();
			for(Element e:beanList){
				beansMap.put(e.attributeValue("name"), e);
			}
			
			//解析actions
			Element actions = root.element("actions");
			List<Element> actionList = actions.elements();
			for(Element e:actionList){
				ConfigBean config = new ConfigBean();
				String formBean = e.attributeValue("form");
				String path = e.attributeValue("path");
				Element formElement = beansMap.get(formBean);
				config.setFormBeanName(formBean);
				config.setFormBeanClassName(formElement.attributeValue("class"));
				config.setPath(path);
				config.setActionClassName(e.attributeValue("class"));
				List<Element> resultList = e.elements();
				for(Element re:resultList){
					String resultName = re.attributeValue("name");
					String resultUrl = re.getText();
					config.addForward(resultName, new ActionForward(resultName, resultUrl));
				}
				configBean.put(path, config);
			}
		} catch (DocumentException e) {
			e.printStackTrace();
		}
		return configBean;
	}
	
	public static void main(String[] args) {
		parser("D:\\my\\workspace\\mvc\\src\\main\\webapp\\WEB-INF\\mvc-config.xml");
	}
}
